# -*-encoding: utf-8 -*-

from pyramid.view import view_config
from pyramid.view import view_defaults
from pyramid.response import Response
from pyramid.httpexceptions import HTTPFound
import json
from ..utils.Hash.HashUtil import HashUtil
from ..utils.Image.ImageUtil import ImageUtil
from ..utils.DB.MySQL import MySqlCRUD
import time, os, uuid, shutil, hashlib
import base64
from ..utils.Queue import UploadTasks
from ..utils.SMS import MobSMS
from ..utils.User.User import User
from ..utils.Cache.TokenCache import TokenCache
from ..utils.Cache.ChecksumCache import ChecksumCache
import logging
from datetime import datetime
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
log = logging.getLogger(__name__)

from AppBase import Base
class ImageFetch(Base):

    @view_config(route_name='AppCommunityUrlFetchRoute', request_method='POST')
    def AppCommunityUrlFetchRoute(self):
        map = {'RetCode': '0', 'message':"Community URL", 'data':'http://tieba.baidu.com/f?kw=%E5%A4%9A%E5%AE%9D%E4%B8%B2%E8%81%94%E7%9B%9F&qq-pf-to=pcqq.c2c'}
        jsonStr = json.dumps(map, ensure_ascii=False)
        return Response(jsonStr)

    @view_config(route_name='AppImageFetchRoute', request_method='POST')
    def AppImageFetchRoute(self):
        selectSQL = ''
        param2 = ''
        postParams =  self.request.POST
        userType = postParams.getone('type')
        category = postParams.getone('category')
        # type 2表示为自己，否则则是查询默认素材和商家素材
        if userType == '2':
            log.debug('[IMAGEFETCH][Type]User')
            tel = postParams.getone('tel')
            tString = postParams.getone('tString')
            eString = postParams.getone('eString')
            tokenString = postParams.getone('tokenString')

            log.debug('[IMAGEFETCH][TEL]' + tel)
            log.debug('[IMAGEFETCH][T_STRING]' + tString)
            log.debug('[IMAGEFETCH][E_STRING]' + eString)
            log.debug('[IMAGEFETCH][TOKEN_STRING]' + tokenString)

            tmpTokenString = self.calculateToken(tString, tel)

            cache = TokenCache()
            result = cache.getCache(tel)
            if (not result) or (result <> tokenString):
                dt = []
                map = {'RetCode': '141', 'message': '获取用户图片需登录!', 'data': dt}
                jsonStr = json.dumps(map, ensure_ascii=False)
                log.error(jsonStr)
                return Response(jsonStr)
            if (eString <> HashUtil.getStringMD5(tel + tString)) or (tokenString <> tmpTokenString):
                dt = []
                map = {'RetCode': '141', 'message': '获取用户图片需登录!!', 'data': dt}
                jsonStr = json.dumps(map, ensure_ascii=False)
                log.error(jsonStr)
                return Response(jsonStr)

            selectSQL = '''
                SELECT material_info.MD5, material_info.name, material_info.category, material_info.material, material_info.size, material_info.weight, material_info.aperture, material_info.price, material_info.description, material_info.path, user_image_info.image_source_type, material_info.url AS url1, user_info.username AS publisher
                    FROM material_info
                    INNER JOIN
                    (
                        user_image_info INNER JOIN user_info
                        ON user_info.ID = user_image_info.user_id
                    )
                    ON material_info.MD5 = user_image_info.MD5
                    WHERE material_info.category = %s AND user_info.tel = %s
                    ORDER BY user_image_info.update_time DESC;
            '''
            param2 = tel
        else:
            print '[IMAGEFETCH][Type]default|sellers'
            selectSQL = '''
                SELECT material_info.MD5, material_info.name, material_info.category, material_info.material, material_info.size, material_info.weight, material_info.aperture, material_info.price, material_info.description, material_info.path, user_image_info.image_source_type, material_info.url AS url1, user_info.username AS publisher
                FROM material_info
                INNER JOIN
                (
                    user_image_info INNER JOIN user_info
                    ON user_info.ID = user_image_info.user_id
                )
                ON material_info.MD5 = user_image_info.MD5
                WHERE material_info.category = %s AND user_info.type = %s
                ORDER BY user_image_info.update_time DESC;
            '''
            param2 = userType
        if category == '0':
            selectSQL = selectSQL.replace('material_info.category = %s AND ', '')
            log.debug(selectSQL)
            resultSelect = MySqlCRUD.selectImpl(selectSQL, param2)
        else:
            log.debug(selectSQL)
            resultSelect = MySqlCRUD.selectImpl(selectSQL, category, param2)
        log.debug(resultSelect)
        for item in resultSelect:
            itemMD5 = item['MD5']
            thumb_path = os.path.join('/media/thumb', itemMD5[0: 2], itemMD5[2: 4], itemMD5 + '.jpg')
            item['thumb_path'] = thumb_path
        map = {'RetCode':'0', 'message':'成功', 'data':resultSelect}
        jsonStr = json.dumps(map, ensure_ascii=False)
        jsonStr = jsonStr.replace('/media', '/static')
        log.debug(jsonStr)
        return Response(jsonStr)



